from app import db

# 食材模型
class Ingredient(db.Model):
    __tablename__ = 'ingredients'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True, nullable=False)
    category = db.Column(db.String(50))
    unit = db.Column(db.String(20))
    
    # 显式定义与Recipe的多对多关系，使用不同的名称避免冲突
    recipe_items = db.relationship('Recipe', secondary='recipe_ingredients', backref=db.backref('ingredients_list', lazy=True), overlaps="recipe_ingredients,ingredients")
    
    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'category': self.category,
            'unit': self.unit
        }

# 营养成分模型
class Nutrition(db.Model):
    __tablename__ = 'nutrition'
    
    id = db.Column(db.Integer, primary_key=True)
    ingredient_id = db.Column(db.Integer, db.ForeignKey('ingredients.id'))
    recipe_id = db.Column(db.Integer, db.ForeignKey('recipes.id'))
    calories = db.Column(db.Numeric(10, 2))
    protein = db.Column(db.Numeric(10, 2))
    carbs = db.Column(db.Numeric(10, 2))
    fat = db.Column(db.Numeric(10, 2))
    
    # 关系定义
    ingredient = db.relationship('Ingredient', backref=db.backref('nutrition', lazy=True))
    recipe = db.relationship('Recipe', backref=db.backref('nutrition', lazy=True))
    
    # 检查约束
    __table_args__ = (
        db.CheckConstraint('ingredient_id IS NOT NULL OR recipe_id IS NOT NULL'),
    )
    
    def to_dict(self):
        return {
            'id': self.id,
            'ingredient_id': self.ingredient_id,
            'recipe_id': self.recipe_id,
            'calories': float(self.calories) if self.calories else None,
            'protein': float(self.protein) if self.protein else None,
            'carbs': float(self.carbs) if self.carbs else None,
            'fat': float(self.fat) if self.fat else None
        }